<template>
  <AuModal
    v-model="showModal"
    :title="t('expiry_manage.form.selected_materials')"
    :width="460"
    :height="600"
    @handleConfirm="modalConfirm"
  >
    <template v-for="(value, key) in cateCheckedNodeList" :key="key">
      <div
        v-if="value && value.length"
        class="px-[12px] mt-[20px] first-of-type:mt-0"
      >
        <div class="text-[#666B71] text-sm">
          {{ key }}
        </div>
        <div class="text-[--autata-font-color] mt-[6px]">
          <template v-for="(item, index) in value" :key="index">
            <span>{{ item.name }} </span>
            <span
              v-if="index !== value.length - 1"
              class="inline-block align-[3px] w-[2px] h-[2px] rounded bg-[--autata-font-color] mx-[4px]"
            />
          </template>
        </div>
      </div>
    </template>
  </AuModal>
</template>

<script setup lang="ts">
import { AuModal } from "@/components/AuModal";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import {
  CategoryProp,
  getCategory,
  getMaterialDetList
} from "@/api/expiry/expiry";
import { cloneDeep } from "lodash-unified";
import { ObjectProps } from "@/components/AuTable/type";

const { t } = useI18n();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  checkList: {
    type: Array as PropType<string>,
    default: () => []
  }
});
const emit = defineEmits(["update:modelValue", "handleConfirm"]);

const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

let categoryList = [];
const cateCheckedNodeList = ref<{ [key: string]: ObjectProps[] }>({});

let tableDataSource = [];

const modalConfirm = () => {
  emit("handleConfirm");
};

function filterCate(data: ObjectProps[], cate: string) {
  return data.filter((item: ObjectProps) => item.type_name === cate);
}

function getCateChecked() {
  for (const item of categoryList) {
    const filterTable = filterCate(tableDataSource, item.name);
    cateCheckedNodeList.value[item.name] = filterTable.filter(v =>
      props.checkList.includes(v.material_id)
    );
  }
}

const init = () => {
  getCategory().then(res => {
    categoryList = res.data;

    getMaterialDetList({}).then(res => {
      tableDataSource = cloneDeep(res.data);
      getCateChecked();
    });
  });
};

watch(
  () => props.checkList,
  () => {
    getCateChecked();
  }
);

onMounted(() => {
  init();
});
</script>
